<?php
/**
 * 애드페이 (AD-Pay for Gnuboard4)
 *
 * Copyright (c) 2010 Choi Jae-Young <www.miwit.com>
 *
 * 저작권 안내
 * - 저작권자는 이 프로그램을 사용하므로서 발생하는 모든 문제에 대하여 책임을 지지 않습니다. 
 * - 이 프로그램을 어떠한 형태로든 재배포 및 공개하는 것을 허락하지 않습니다.
 * - 이 저작권 표시사항을 저작권자를 제외한 그 누구도 수정할 수 없습니다.
 */

if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가

// 광고 날짜 계산
function mw_pay_banner_period($pr_id, $or_edate='')
{
    global $g4, $pb;

    $product = sql_fetch("select * from $pb[product_table] where pr_id = '$pr_id'");

    $the_time = $g4[server_time];
    if ($or_edate)
        $the_time = strtotime("$or_edate 00:00:00");

    $or_sdate = date("Y-m-d", strtotime("+ 1 day", $the_time));

    $sql = " select count(or_id) as cnt from $pb[order_table] ";
    $sql.= " where pr_id = '$pr_id' and or_app = '1' and '$or_sdate' between or_sdate and or_edate";
    $row = sql_fetch($sql);

    if ($row[cnt] >= $product[pr_reg_count]) {
        $sql = "select * from $pb[order_table] where pr_id = '$pr_id' order by or_edate desc limit ".($product[pr_reg_count]-1).", 1 ";
        $row = sql_fetch($sql);
        $or_sdate = date("Y-m-d", strtotime("+1 day", strtotime("{$row[or_edate]} 00:00:00")));
    }

    /*$i = 1;
    do {
        $or_sdate = date("Y-m-d", strtotime("+".$i++." day", $g4[server_time]));
        $sql = "select count(or_id) as cnt from $pb[order_table] where pr_id = '$pr_id' and '$or_sdate' between or_sdate and or_edate";
        $row = sql_fetch($sql);
    } while ($row[cnt] >= $product[pr_reg_count]);*/

    return $or_sdate;
}

// 광고출력
function mw_pay_banner($pr_code, $skin, $opt='')
{
    global $g4, $pb;

    $product = sql_fetch("select * from $pb[product_table] where pr_code = '$pr_code'");
    if (!$product) {
        echo "[$pr_code] 존재하지 않는 광고코드 입니다.";
        return;
    }

    $list = array();

    $sql_order = "";
    switch ($product['pr_order']) {
        case 'rand': $sql_order = " order by rand() "; break;
        case 'date': $sql_order = " order by or_datetime "; break;
        case 'date_desc': $sql_order = " order by or_datetime desc "; break;
        case 'edate': $sql_order = " order by or_edate "; break;
        case 'edate_desc': $sql_order = " order by or_edate desc "; break;
    }

    $sql = "select * from $pb[order_table]
             where pr_id = '$product[pr_id]' 
               and '$g4[time_ymd]' between or_sdate and or_edate 
               and or_app = '1'
             $sql_order
             limit $product[pr_reg_count]";
    $qry = sql_query($sql);
    for ($i=0; $row=sql_fetch_array($qry); $i++)
    {
        $target = $row[or_target];
        if (!$target) $target = $row[pr_target];
        if (!$target) $target = "_blank";

        $row[href] = "$pb[path]/click.php?or_id=$row[or_id]";
        if ($row['or_type'] == '' || $row['or_type'] == 'i') {
            $row[view] = mw_pay_banner_view($row[or_file], $row[href],
                $product[pr_width], $product[pr_height], "title='$row[or_site] - $row[or_info]'", $target);
        }
        else {
            $row['view'] = $row['or_code'];
        }
        $row[target] = $target;
        $list[$i] = $row;
    }
    //if ($product['pr_shuffle']) shuffle($list);

    for ($j=$i; $j<$product[pr_reg_count]; $j++) {
        $target = $product[pr_target];
        if (!$target) $target = "_blank";

        $list[$j][href] = "$pb[path]/click.php?pr_id=$product[pr_id]";

        if ($list[$j]['or_type'] == '' || $list[$j]['or_type'] == 'i') {
            $list[$j]['view'] = mw_pay_banner_view($product[pr_default_file],
                $product[pr_default_url], $product[pr_width], $product[pr_height], '', $product[pr_target]);
        }
        else {
            $list[$j][view] = $product['pr_default_code'];
        }
        $list[$j][target] = $target;
        $list[$j][or_file] = $product[pr_default_file];
    }

    $pb_skin_path = "$pb[skin_path]/$skin";

    ob_start();
    include("$pb_skin_path/banner.skin.php");
    $content = ob_get_contents();
    ob_clean();

    return $content;
}

function mw_pay_banner_view($file, $href, $width, $height, $ext='', $target='_blank')
{
    global $g4, $pb, $pr_code;

    $file_path = "$pb[banner_path]/".urlencode($file);
    $res = "";

    if (!file_exists($file_path)) {
        ;
    }
    else if (preg_match("/\.(jpg|gif|png)$/i", $file)){
        $res = "<img src=\"$file_path\" width=\"$width\" height=\"$height\" $ext>";
        if ($href)
            $res = "<a href=\"$href\" target=\"$target\" class=\"adpay-$pr_code\">$res</a>";  
    }
    else if (preg_match("/\.(swf)$/i", $file)) {
        $res = "<script>doc_write(flash_movie(\"$file_path\", \"_g4_{$or_id}\", \"$width\", \"$height\", \"transparent\"));</script>";
    }
    return $res;
}

function mw_pay_banner_hit($or_id)
{
    global $g4, $pb, $member;

    if (!$or_id) return;
    //if (stristr($_SERVER[HTTP_USER_AGENT], "bot")) return;

    // 한번 읽은글은 브라우저를 닫기전까지는 카운트를 증가시키지 않음
    $ss_name = "ss_adpay_{$or_id}";
    if (!get_session($ss_name))
    {
        set_session($ss_name, TRUE);

        sql_query("update $pb[order_table] set or_hit = or_hit + 1 where or_id = '$or_id' ");

        global $pb_output_sql;

        $this_month_output_table = "$pb[output_table]_".date("ym", $g4[server_time]);
        $tmp = sql_query("show tables like '$this_month_output_table'");
        if (!mysql_num_rows($tmp))
            sql_query(str_replace($pb[output_table], $this_month_output_table, $pb_output_sql));

        $sql = "insert into $this_month_output_table set or_id = '$or_id' ";
        $sql.= ", ou_ip = '$_SERVER[REMOTE_ADDR]' ";
        $sql.= ", ou_agent = '$_SERVER[HTTP_USER_AGENT]' ";
        $sql.= ", mb_id = '$member[mb_id]' ";
        $sql.= ", ou_date = '$g4[time_ymd]' ";
        $sql.= ", ou_time = '$g4[time_his]'";
        $qry = sql_query($sql, false);
    }
}

